package Server;

import java.io.RandomAccessFile;
import java.util.ArrayList;

public class CommaSeperatedFile implements Database {

	public static final String NAME = "CVS";

	private static Database _instance = null;
	private RandomAccessFile raf;
	private String table;


	protected CommaSeperatedFile() {
		setTable("GETALLEN");
		initRaf();
	}

	@Override
	public boolean insert(ArrayList<Integer> data) {
		try {
			raf.seek(raf.length()+1);
			for(Integer i : data) {
				raf.writeBytes(i.toString() + ",");
			}
		} catch (Exception e) {
			return false;
		}
		return true;
	}

	@Override
	public ArrayList<Integer> get() {
			StringBuffer sb = new StringBuffer();
			ArrayList<Integer> al = new ArrayList<Integer>();		

			try {
				int length = (int)raf.length();

				raf.seek(0);

				for (int i = 0; i<length; i++) {
					sb.append((char)raf.readByte());
				}
			} catch (Exception e) {
				System.out.println(e);
			}

			String string = sb.toString();
			String[] array = string.split(",");
			try {
			for (int i = 0; i < array.length; i++) {
				Integer num = Integer.parseInt(array[i].trim());
				al.add(num);			
			}
			} catch (Exception e) {
				System.out.println("Error reading file, might not exist or is corrupted.");
			}
			return al; 
	}

	public static Database getInstance() {
		synchronized (CommaSeperatedFile.class) {
			if (_instance == null) {
				_instance = new CommaSeperatedFile();
				return _instance;
			}
			return null;
		}

	}

	public static void release() {
		synchronized(CommaSeperatedFile.class){
			if (_instance != null)
				_instance = null;
		}
	}

	public void setTable(String table) {
		this.table = table + ".csv";
	}

	private void initRaf() {
		try {
			raf = new RandomAccessFile(table, "rw");
			if (raf.length() < 1) {
				ArrayList<Integer> a = new ArrayList<Integer>();
				a.add(1);
				a.add(2);
				insert(a);
			}
		} catch (Exception e) {
			System.out.println(e);
		}
	}
}
